import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import { Avatar, Badge, Button, Dropdown, Input, MenuProps } from 'antd';
import Tooltips from '@/components/Antd/Tooltips';
import useModal from '@/hooks/use-modal/useModal';
import ModelSelect from '../ModelSelect';
import ModelInput from '../ModelInput';
import ModelConfig from '../ModelConfig';
import modelService from '@/api/services/modelService';
import useTable from '@/hooks/use-table';
import {
  GetCreatedListItem,
  GetDefaultListRes,
  GetModelListModels,
  GetProviderListItem,
  GetProviderListReq,
} from '@/common/types';
import ModelAdd from '../ModelAdd';
import { SvgIcon } from '@/components/icon';
import TipsModals from '@/components/modals/TipsModals';
import { useSearchParams } from 'react-router-dom';
import { CircleLoading } from '@/components/loading';
import Modals from '@/components/modals/Modals';
import GradientBox from '@/components/GradientBox';
import NotData from '@/components/NotData';

const index = forwardRef((_, ref) => {
  const modal = useModal('check', 'config', 'select', 'input', 'addModel', 'delete');
  const [updateData, setUpdateData] = useState<GetProviderListItem | GetCreatedListItem>();
  const [defaultModelAdd, setDefaultModelAdd] = useState<GetModelListModels>();
  const [refresh, setRefresh] = useState(0);
  const [modelInputStatus, setModelInputStatus] = useState(false);
  const [deleteData, setDeleteData] = useState<GetCreatedListItem>();
  const [defaultModelData, setDefaultModelData] = useState<GetDefaultListRes>();

  const [userInput, setUserInput] = useState<any>();

  const [deleteProviderLoading, setDeleteProviderLoading] = useState<boolean>(false);
  const [deleteProviderValue, setDeleteProviderValue] = useState<number>(0);

  const [customStatus, setCustomStatus] = useState(false);

  const [modelList, setModelList] = useState<number>(0);

  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    openConfig: () => modal.config.open(),
  }));

  const {
    tablesValue,
    getTables,
    loading,
    pagingInfo,
    handleSearchText,
    searchText,
    setTablesValue,
  } = useTable<GetCreatedListItem>(modelService.getCreatedList, {
    pageSize: 9999,
    page: 1,
  });

  useEffect(() => {
    getTables();
    getDefaultList();
  }, []);

  useEffect(() => {
    if (!modal.input.isOpen) {
      setCustomStatus(false);
    }
  }, [modal.input]);

  const getDefaultList = () => {
    modelService.getDefaultList().then((res) => {
      setDefaultModelData(res);
    });
  };

  const formatData = (value: any) => {
    const result = [];
    const chat = value.chat;
    const embedding = value.embedding;
    const funcCall = value.funcCall;
    const rerank = value.rerank;

    for (const key in chat) {
      if (chat.hasOwnProperty(key)) {
        result.push({ type: 'chat', value: key, id: chat[key] });
      }
    }
    for (const key in embedding) {
      if (embedding.hasOwnProperty(key)) {
        result.push({ type: 'embedding', value: key, id: embedding[key] });
      }
    }
    for (const key in funcCall) {
      if (funcCall.hasOwnProperty(key)) {
        result.push({ type: 'funcCall', value: key, id: funcCall[key] });
      }
    }
    for (const key in rerank) {
      if (rerank.hasOwnProperty(key)) {
        result.push({ type: 'rerank', value: key, id: rerank[key] });
      }
    }

    return result;
  };

  const handleUpdateModel = (value: GetProviderListItem) => {
    if (value.name.length === 0) {
      setCustomStatus(true);
    }
    setUpdateData(value);
    modal.select.close();
    modal.input.open();
    if (value.isThirdParty) {
      setModelInputStatus(true);
    }
  };

  const addModelSubmit = () => {
    setRefresh(refresh + 1);
    modal.addModel.close();
  };

  const handleCardClick = (value: GetCreatedListItem, status: boolean = false) => {
    setModelInputStatus(status);
    setUpdateData(value);
    modal.input.open();
  };

  const handleInputClose = (value?: boolean) => {
    if (value) {
      getTables();
    }
    setModelInputStatus(false);
    modal.input.close();
  };

  const handleInputOk = (value?: boolean) => {
    if (value) {
      getTables();
    }
    setModelInputStatus(false);
    modal.input.close();
  };

  const handleModelAddDefault = (value: GetModelListModels) => {
    setDefaultModelAdd(value);
    modal.addModel.open();
  };

  const handleDeleteModel = (value: GetCreatedListItem) => {
    setDeleteData(value);
    modal.delete.open();
    setDeleteProviderLoading(true);

    modelService
      .getModelList({
        page: 1,
        pageSize: 999,
        searchText: '',
        provider: [value.isLocal ? 'Ruijie' : value.name],
      })
      .then((res) => {
        const usedCount = res.list.reduce((acc, cur) => acc + (cur.usedCount || 0), 0);
        setDeleteProviderValue(usedCount);
      })
      .finally(() => {
        setDeleteProviderLoading(false);
      });
  };

  const onDeleteModel = () => {
    if (deleteData) {
      modal.delete.startLoading();
      modelService
        .deleteProvider(deleteData?.id)
        .then((res) => {
          getTables();
          modal.delete.close();
        })
        .finally(() => {
          modal.delete.stopLoading();
        });
    }
  };

  const handleModelAddClose = () => {
    modal.addModel.close();
    setDefaultModelAdd(undefined);
  };

  const handleSubmitConfig = () => {
    getDefaultList();
    modal.config.close();
  };

  const handleUpdateModelValue = (value: any, list?: any) => {
    if (list) {
      setModelList(list.length);
    }
    setUserInput(value);
    modal.addModel.open();
  };

  const handeSetList = (value: any) => {
    if (inputRef.current) {
      inputRef.current?.setTablesValue((prev) => {
        const next = [...prev];
        const index = next.findIndex((item) => item.metadata.model === value.name);

        if (index >= 0) {
          const temp = next.find((item) => item.metadata.model === value.name);
          next.splice(index, 1, {
            metadata: {
              ...value,
              model: value.name,
              reasoning: value.enableReasoning,
              isActive: temp.metadata.isActive,
              isCustom: true,
              type: value.modelType,
            },
          });
          return [...next];
        } else {
          return [
            ...prev,
            {
              metadata: {
                ...value,
                model: value.name,
                reasoning: value.enableReasoning,
                isActive: false,
                isCustom: true,
                type: value.modelType,
              },
            },
          ];
        }
      });
      modal.addModel.close();
    }
  };

  const hanldeDeleteSetList = (value: any) => {
    inputRef.current?.setTablesValue((prev) => {
      return prev.filter((item) => item.metadata.model !== value.metadata.model);
    });
    modal.addModel.close();
  };

  return (
    <>
      <div className="flex items-center justify-between gap-3">
        <Input
          placeholder="搜索"
          style={{ width: 240 }}
          suffix={<SvgIcon icon="work-ic6" size={16} color="text-text-4" />}
          value={searchText}
          onChange={(e) => handleSearchText(e.target.value)}
        />
        {/* <Button type="primary" icon={<PlusOutlined />} onClick={modal.select.open}>
          新增
        </Button> */}
        <div
          className=" flex  h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md  border !border-@brand-color !text-@brand-color"
          onClick={modal.select.open}
        >
          <SvgIcon icon="message-ic13" size="15" className="mr-1" />
          新增
        </div>
        {/* <Badge
          dot={defaultModelData && Object.values(defaultModelData).some((item) => item === null)}
        >
          <Button onClick={modal.config.open}>默认模型配置</Button>
        </Badge> */}
      </div>

      <div
        className={`mt-4  ${loading || tablesValue.length === 0 ? 'h-full w-full' : 'grid-row'}`}
      >
        {loading ? (
          <>
            <CircleLoading />
          </>
        ) : tablesValue.length === 0 ? (
          <>
            <NotData />
          </>
        ) : (
          tablesValue
            .sort((a, b) => (a.isLocal === b.isLocal ? 0 : a.isLocal ? -1 : 1))
            .filter((item) =>
              item.name.toLocaleLowerCase().includes(searchText.toLocaleLowerCase()),
            )
            .map((item, index) => {
              let menuItems: MenuProps['items'] = [
                {
                  key: '1',
                  label: '查看详情',
                  onClick: (e) => {
                    e.domEvent.stopPropagation();
                    handleCardClick(item);
                  },
                },
              ];

              if (!item.isLocal) {
                menuItems = [
                  {
                    key: '2',
                    label: '编辑',
                    onClick: (e) => {
                      e.domEvent.stopPropagation();
                      handleCardClick(item, true);
                    },
                  },
                  {
                    key: '3',
                    danger: true,
                    label: '删除',
                    onClick: (e) => {
                      e.domEvent.stopPropagation();
                      handleDeleteModel(item);
                    },
                  },
                ];
              }

              return (
                <GradientBox
                  className="relative flex h-[120px] cursor-pointer flex-col justify-between rounded-xl bg-[#FFFFFFD9]"
                  style={{
                    border: '1px solid #fff',
                  }}
                  key={index.toString()}
                  onClick={() => handleCardClick(item, true)}
                >
                  <div className="flex flex-1  items-center p-4 pb-0">
                    <div
                      className="w-10 rounded-full"
                      style={{
                        border: '1px solid #00134D0A',
                      }}
                    >
                      <SvgIcon
                        icon={item.avatar === 'Custom' ? 'CustomModel' : item.avatar}
                        size={40}
                        color="#fff"
                      />
                    </div>
                    <div
                      className="text-truncate ml-4 text-base font-bold text-text-5"
                      style={{ maxWidth: 'calc(100% - 90px)' }}
                    >
                      {item.name}
                    </div>
                  </div>

                  <div className="flex items-center justify-between p-4 pt-0">
                    <div className="flex gap-1">
                      {item.isLocal && (
                        <div className="rounded-small bg-@brand-color-light px-2 text-sm leading-[22px] text-@brand-color">
                          本地
                        </div>
                      )}
                      <div className="text-text-3">{item.isLocal ? '预载模型' : '第三方模型'}</div>
                    </div>
                    <Dropdown menu={{ items: menuItems }} trigger={['click']}>
                      <div
                        onClick={(e) => {
                          e.stopPropagation();
                        }}
                        className="flex h-6 w-6 items-center justify-center hover:rounded-md hover:bg-fill-2 hover:!text-text-5 "
                      >
                        <SvgIcon icon="work-more" size={20} />
                      </div>
                      {/* <EllipsisOutlined
                        className="text-[24px] text-text-4"
                        onClick={(e) => {
                          e.stopPropagation();
                        }}
                      /> */}
                    </Dropdown>
                  </div>

                  {item.status !== '0' && (
                    <Tooltips
                      placement="topRight"
                      title={
                        item.status === '2'
                          ? '供应商部分模型失效，请注意'
                          : '所有模型已失效，请检查供应商状态'
                      }
                    >
                      <div
                        className={`absolute right-[1px] top-[1px] flex items-center px-[10px] py-[2px] text-xs ${
                          item.status === '2'
                            ? 'bg-@warning-color-light text-@warning-color'
                            : 'bg-@error-color-light text-@error-color'
                        }`}
                        style={{
                          borderTopRightRadius: 8,
                          borderBottomLeftRadius: 12,
                        }}
                      >
                        <div
                          className={`mr-[6px] h-1 w-1 rounded-full ${
                            item.status === '2' ? 'bg-@warning-color' : 'bg-@error-color'
                          }`}
                        />
                        <div>{item.status === '2' ? '波动' : '失效'}</div>
                      </div>
                    </Tooltips>
                  )}
                </GradientBox>
              );
            })
        )}
      </div>

      {/* <ModelConfig
        open={modal.config.isOpen}
        onCancel={modal.config.close}
        onOk={handleSubmitConfig}
        defaultList={defaultModelData}
      /> */}
      <ModelSelect
        open={modal.select.isOpen}
        onCancel={modal.select.close}
        onOk={handleUpdateModel}
        selectProvider={tablesValue}
      />
      <ModelInput
        modelData={updateData}
        open={modal.input.isOpen}
        onCancel={handleInputClose}
        onSubmit={handleInputOk}
        updateModel={handleUpdateModelValue}
        refresh={refresh}
        openSetting={handleModelAddDefault}
        status={modelInputStatus}
        updateTables={getTables}
        ref={inputRef}
        customStatus={customStatus}
      />
      <ModelAdd
        open={modal.addModel.isOpen}
        onCancel={handleModelAddClose}
        onOk={addModelSubmit}
        modelData={updateData}
        defaultValue={defaultModelAdd}
        userInput={userInput}
        customStatus={customStatus}
        setList={handeSetList}
        hanldeDeleteSetList={hanldeDeleteSetList}
        listNumber={modelList}
        closeInput={handleInputClose}
      />
      <TipsModals
        open={modal.delete.isOpen}
        onOk={onDeleteModel}
        confirmLoading={modal.delete.isLoading}
        onCancel={modal.delete.close}
        footerOkDisabled={deleteProviderLoading}
      >
        {deleteProviderLoading ? (
          <div className="h-12">
            <CircleLoading />
          </div>
        ) : (
          <div>
            {deleteProviderValue < 1
              ? '确认要删除？删除后无法恢复。'
              : `该供应商已被${deleteProviderValue}个应用使用，会影响当前应用效果，确认删除？`}
          </div>
        )}
      </TipsModals>
    </>
  );
});

export default index;
